package com.ruoyi.manage.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

import cn.hutool.db.dialect.DialectName;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.manage.domain.GoodsShelves;
import com.ruoyi.manage.domain.Lovehouse;
import com.ruoyi.manage.domain.Vm;
import com.ruoyi.manage.domain.vo.DonationVo;
import com.ruoyi.manage.mapper.GoodsShelvesMapper;
import com.ruoyi.manage.mapper.LovehouseMapper;
import com.ruoyi.manage.mapper.VmMapper;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.manage.mapper.DonationMapper;
import com.ruoyi.manage.domain.Donation;
import com.ruoyi.manage.service.IDonationService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 捐赠物品Service业务层处理
 * 
 * @author zzg
 * @date 2025-03-21
 */
@Service
public class DonationServiceImpl implements IDonationService 
{
    @Autowired
    private DonationMapper donationMapper;
    @Autowired
    private GoodsShelvesMapper goodsShelvesMapper;
    @Autowired
    private VmMapper vmMapper;
    @Autowired
    private LovehouseMapper  lovehouseMapper;

    /**
     * 查询捐赠物品
     * 
     * @param id 捐赠物品主键
     * @return 捐赠物品
     */
    @Override
    public Donation selectDonationById(Long id)
    {
        return donationMapper.selectDonationById(id);
    }

    @Override
    public DonationVo selectDonationVoById(Long id) {
        return donationMapper.selectDonationVoById(id);
    }

    /**
     * 查询捐赠物品列表
     * 
     * @param donation 捐赠物品
     * @return 捐赠物品
     */
    @Override
    public List<Donation> selectDonationList(Donation donation)
    {
        return donationMapper.selectDonationList(donation);
    }

    @Override
    public List<DonationVo> selectDonationVoList(Donation donation) {
        return donationMapper.selectDonationVoList(donation);
    }

    /**
     * 新增捐赠物品
     * 
     * @param donation 捐赠物品
     * @return 结果
     */
    @Override
    public int insertDonation(Donation donation)
    {
        donation.setDonorId(donation.getDonorId()==null?8:donation.getDonorId());
        int num = donationMapper.selectCountByOddNumber(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        if(num>=1000){
            donation.setOddNumber(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))+num);
        }else {
            donation.setOddNumber(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))+String.format("%04d", num+1));
        }
        donation.setStatus(0);
        donation.setCreateTime(DateUtils.getNowDate());
        return donationMapper.insertDonation(donation);
    }

    /**
     * 修改捐赠物品
     * 
     * @param donation 捐赠物品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDonation(Donation donation)
    {
        donation.setUpdateTime(DateUtils.getNowDate());
        /*管理员入库*/
        if(donation.getStatus()==3){
            donation.setStorageTime(DateUtils.getNowDate());
        }
        /*审核通过=>分配货架*/
        //1.判断状态
        if(donation.getStatus()==2){
            //2.货架是否关联
            GoodsShelves shelves = GoodsShelves.builder().donationId(donation.getId()).build();
            List<GoodsShelves> list = goodsShelvesMapper.selectGoodsShelvesList(shelves);
            if(list.size()==0||list==null){
                //3.分配货架
                //根据小屋id查询设备id集合
                List<Long> ids = vmMapper.selectVmList(
                        Vm.builder().lovehouseId(donation.getLovehouseId()).build())
                        .stream().map(Vm::getId).collect(Collectors.toList());
                //4.根据设备id集合查询货架集合
                for (Long id : ids) {
                    List<GoodsShelves> shelvesList = goodsShelvesMapper.selectGoodsShelvesList(
                            GoodsShelves.builder().vmId(id).shelfStatus(2).build());
                    if(shelvesList.size()==0||shelvesList==null)continue;//无可用货架,继续查
                    GoodsShelves goodsShelves = shelvesList.get(0);
                    goodsShelves.setDonationId(donation.getId());
                    goodsShelves.setShelfStatus(3);//预占用
                    goodsShelves.setUpdateTime(DateUtils.getNowDate());
                    goodsShelvesMapper.updateGoodsShelves(goodsShelves);//更新货架信息
                    return donationMapper.updateDonation(donation);
                }
                throw new RuntimeException("货架已满");
            }
        }
        return donationMapper.updateDonation(donation);
    }

    /**
     * 批量删除捐赠物品
     * 
     * @param ids 需要删除的捐赠物品主键
     * @return 结果
     */
    @Override
    public int deleteDonationByIds(Long[] ids)
    {
        return donationMapper.deleteDonationByIds(ids);
    }

    /**
     * 删除捐赠物品信息
     * 
     * @param id 捐赠物品主键
     * @return 结果
     */
    @Override
    public int deleteDonationById(Long id)
    {
        return donationMapper.deleteDonationById(id);
    }

    /**
     * 根据学校id查询捐赠物品
     * @param donation
     * @param schoolId
     * @return
     */
    public List<?> selectDonationVoListBySchoolId(Donation donation, Long schoolId) {
        if(schoolId!=null&&schoolId!=0){//表示需要根据小屋id查询
            List<Lovehouse> lovehouses = lovehouseMapper.selectLovehouseListBySchoolId(schoolId);
            if(lovehouses.isEmpty()){//如果该学校下没有小屋,直接返回空集合
                List<Donation> donations = new ArrayList<>();
                return donations;
            }
            StringJoiner ids = new StringJoiner(",");
            for (Lovehouse lovehouse : lovehouses) {
                ids.add(String.valueOf(lovehouse.getId()));
            }
            PageUtils.startPage();
            return donationMapper.selectDonationVoListByHouseIds(donation,ids.toString());
        }
        PageUtils.startPage();
        return donationMapper.selectDonationVoList(donation);
    }
}
